//ICC-AVR application builder : 2009/7/29 10:40:45
// Target : M16
// Crystal: 16.000Mhz

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>


unsigned int angles[19]={0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180};
unsigned int angle_counts[19];
volatile int sequence=0;

void angle_to_counts()
{
    int i;
    for(i=0;i<19;i++)
    {
        angle_counts[i]=angles[i]*250/90+125+0xFFFF-5000;
    }
}

void led_flash()
{
    PORTB |=1<<1;
    _delay_ms(100);
    PORTB &=~(1<<1);
}

void port_init(void)
{
 PORTA = 0xFF;
 DDRA  = 0xFF;
 PORTB = 0x01;
 DDRB  = 0x1B;
 PORTC = 0xFF; //m103 output only
 DDRC  = 0xFF;
 PORTD = 0x00;
 DDRD  = 0x00;
}

//TIMER1 initialize - prescale:64
// WGM: 0) Normal, TOP=0xFFFF
// desired value: 250000Hz
// actual value: 250000.000Hz (0.0%)
void timer1_init(void)
{
 TCCR1B = 0x00; //stop
 TCNT1 = 0xFFFF-5000; //setup
 OCR1A = angle_counts[sequence];
 TCCR1A = 0x00;
 TCCR1B = 0x03; //start Timer
}

ISR(TIMER1_COMPA_vect)
{
 //compare occured TCNT1=OCR1A
 PORTA &=~1;
}

ISR(TIMER1_OVF_vect)
{
 //TIMER1 has overflowed
 TCNT1 = 0xFFFF-5000; //reload counter high value
 OCR1A = angle_counts[sequence];
 PORTA |=1;
}

ISR(INT0_vect)
{
 //external interupt on INT0
}

ISR(INT1_vect)
{
 //external interupt on INT1
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 cli(); //disable all interrupts
 port_init();
 timer1_init();

 MCUCR = 0x00;
 GICR  = 0xC0;
 TIMSK = 0x14; //timer interrupt sources
 sei(); //re-enable interrupts
 //all peripherals are now initialized
}



int main()
{
    angle_to_counts();
    init_devices();

    while(1)
    {
        _delay_ms(3000);
        led_flash();
        sequence++;
        sequence%=19;
    }
    return 0;
}

